<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class Mqtt extends Command
{
    protected function configure(): void
    {
        // 指令配置
        $this->setName('subscribe')->setDescription('充电宝mqtt服务');
    }

    protected function execute(Input $input, Output $output): void
    {
        // 指令输出
        $output->writeln('mqtt服务启动成功');
        try {
            // 通过 ConnectionSettings 设置连接参数
            $settings = (new \PhpMqtt\Client\ConnectionSettings)->setUsername('php_service')->setPassword('Developerphp@123');
            $mqtt = new \PhpMqtt\Client\MqttClient('47.102.117.21', 1883, 'test-subscriber');
            $mqtt->connect($settings, true);
            $mqtt->subscribe('/RYB/RYB10000000B/user/update', function($topic, $message, $retained, $matchedWildcards) {
                echo sprintf("Received message on topic [%s]: %s\n", $topic, $message);
            }, 0);
            $mqtt->loop(true);
        }catch (\Exception $e){
            echo ("mqtt subscribe service throw bad message:" . $e->getMessage() . '//' . $e->getLine() . ' in ' . $e->getFile());
        }
    }

}
